#![allow(unused)]

use std::{fs::File, io::Cursor};

use ab_glyph::FontRef;
use axum::{http::header, response::IntoResponse, routing::get, Router};
use image::{io::Reader as ImageReader, ImageFormat};
use imageproc::drawing;
use tokio::net::TcpListener;

#[tokio::main]
async fn main() {
    let listener = TcpListener::bind(&"0.0.0.0:56789").await.unwrap();
    let app = Router::new().route("/", get(handler));

    axum::serve(listener, app.into_make_service())
        .await
        .unwrap();
}

async fn handler() -> impl IntoResponse {
    let mut img = image::open("output.jpg").unwrap();
    let font = FontRef::try_from_slice(include_bytes!("../jxzk.ttf")).unwrap();
    drawing::draw_text_mut(
        &mut img,
        image::Rgba([255u8, 255u8, 255u8, 255u8]),
        0,
        0,
        100f32,
        &font,
        "Hello, 世界",
    );
    let mut buf = vec![];
    img.write_to(&mut Cursor::new(&mut buf), ImageFormat::Jpeg)
        .unwrap();

    ([(header::CONTENT_TYPE, "image/jpeg")], buf)
}

fn scale() {
    let img = ImageReader::open("origin.jpg").unwrap().decode().unwrap();
    let scaled = img.thumbnail(img.width() / 10, img.height() / 10);
    let mut output = File::create("output.jpg").unwrap();
    scaled.write_to(&mut output, ImageFormat::Jpeg).unwrap();
}

fn write_watermark() {
    let mut img = image::open("output.jpg").unwrap();
    let font = FontRef::try_from_slice(include_bytes!("../jxzk.ttf")).unwrap();
    drawing::draw_text_mut(
        &mut img,
        image::Rgba([255u8, 255u8, 255u8, 255u8]),
        0,
        0,
        100f32,
        &font,
        "Hello, 世界",
    );
    let mut output = File::create("watermark.jpg").unwrap();
    img.write_to(&mut output, ImageFormat::Jpeg).unwrap();
}
